package com.dao.mybatis.dao;

import java.util.ArrayList;
import java.util.List;

import com.bean.Customer;
import com.dao.CustomerDao;
import com.dao.mybatis.ConnectionFactory;
import org.apache.ibatis.session.SqlSession;

/**
 * @author apodoprigora
 */
public class MyBatisCustomerDao implements CustomerDao {

    public int insert(final Customer object) {
        final SqlSession session = ConnectionFactory.getSession().openSession(true);
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final int result = dao.insert(object);
        session.close();
        return result;
    }


    public List<Integer> insert(final List<Customer> objects) {
        final SqlSession session = ConnectionFactory.getSession().openSession(false);
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final List<Integer> result = new ArrayList<Integer>();
        for (final Customer object : objects) {
            result.add(dao.insert(object));
        }
        session.commit();
        session.close();
        return result;
    }


    public int delete(final Customer object) {
        final SqlSession session = ConnectionFactory.getSession().openSession(true);
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final int result = dao.delete(object);
        session.close();
        return result;
    }


    public int delete(final List<Customer> objects) {
        final SqlSession session = ConnectionFactory.getSession().openSession(false);
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final List<Integer> result = new ArrayList<Integer>();
        for (final Customer object : objects) {
            result.add(dao.delete(object));
        }
        session.commit();
        session.close();
        return result.size();
    }


    public boolean deleteAll() {
        return false;
    }


    public boolean update(final Customer object) {
        final SqlSession session = ConnectionFactory.getSession().openSession(true);
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final boolean result = dao.update(object);
        session.close();
        return result;
    }


    public Customer find(final Integer id) {
        final SqlSession session = ConnectionFactory.getSession().openSession();
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final Customer result = dao.find(id);
        session.close();
        return result;
    }


    public List<Customer> selectAll() {
        final SqlSession session = ConnectionFactory.getSession().openSession();
        final CustomerDao dao = session.getMapper(CustomerDao.class);
        final List<Customer> result = dao.selectAll();
        session.close();
        return result;
    }
}
